package name.fowler.refactoring.simplestore.web;

import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * User: RedSmog
 * Date: 27.11.13
 * Time: 8:42
 */

@WebServlet("/cc/*")
public class ContentController extends HttpServlet {
    @Inject
    private ContentHandler contentHandler;

    @PersistenceUnit
    private EntityManagerFactory factory;

    @Override
    protected void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException {
        String pathInfo = httpServletRequest.getPathInfo();
        String[] pathItem = pathInfo.substring(1).split("/");
        Map<String,String[]> params = httpServletRequest.getParameterMap();

        EntityManager entityManager = factory.createEntityManager();
        try{

            if (params.containsKey("isDelete")) {
                contentHandler.deleteEntity(pathItem, params, entityManager);
            } else {
                contentHandler.addEntity(pathItem, params, entityManager);
            }
            contentHandler.showContent(entityManager, httpServletRequest, httpServletResponse);

        } finally {
            entityManager.close();
        }
    }

    @Override
    protected void doGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException {
        EntityManager entityManager = factory.createEntityManager();
        try{
            contentHandler.showContent(entityManager, httpServletRequest, httpServletResponse);
        } finally {
            entityManager.close();
        }
    }

}
